package com.letv.core.utils;

import java.util.LinkedHashMap;
import java.util.Map;

import android.app.Activity;
import android.text.TextUtils;

/**
 * 管理所有activity的工具类
 * 
 * @author zhuqiao
 *
 */
public class ActivityUtils {

    /**
     * 保存所有activity
     */
    private Map<String, Activity> mActivityMap = new LinkedHashMap<String, Activity>();

    private static ActivityUtils instance = null;

    private ActivityUtils() {
    }

    public static ActivityUtils getInstance() {
        if (instance == null) {
            instance = new ActivityUtils();
        }

        return instance;
    }

    /**
     * 添加activity
     * 
     * @param name activity名称
     * @param activity
     */
    public void addActivity(String name, Activity activity) {
        if (TextUtils.isEmpty(name) || activity == null) {
            return;
        }

        // 保持单例
        removeActivity(name, true);
        mActivityMap.put(name, activity);
    }

    /**
     * 删除activity
     * 
     * @param name activity名称
     * @param finish 是否finish
     */
    public void removeActivity(String name, boolean finish) {
        if (TextUtils.isEmpty(name)) {
            return;
        }

        if (mActivityMap.containsKey(name)) {
            if (finish) {
                Activity activity = mActivityMap.get(name);
                if (activity != null && !activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
    }

    /**
     * 删除所有activity除了@name
     * 
     * @param name activity名称
     */
    public void removeActivitiesExcept(String name) {
        if (TextUtils.isEmpty(name))
            return;

        if (!mActivityMap.isEmpty()) {
            for (String key : mActivityMap.keySet()) {
                if (key.equals(name))
                    continue;

                Activity activity = mActivityMap.get(key);
                if (activity != null && !activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
    }

    /**
     * 删除所有activity
     */
    public void removeAll() {
        if (!mActivityMap.isEmpty()) {
            for (String key : mActivityMap.keySet()) {
                Activity activity = mActivityMap.get(key);
                if (activity != null && !activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
    }

}
